"use strict";

const Controller = require("egg").Controller;

const jwt = require("jsonwebtoken");

class LoginController extends Controller {
  async index() {
    const { ctx, app } = this;

    const { username, password } = ctx.request.body;

    const data = await app.mysql.get("user", { username, password });

    if (data) {
      if (data.status) {
        ctx.body = {
          code: 1,
          msg: "登录成功",
          token: jwt.sign(data.id, "1908A"),
          user: data,
        };
      } else {
        ctx.status = 401;

        ctx.body = {
          code: 0,
          msg: "账户已被锁定,请联系管理员",
        };
      }
    } else {
      ctx.status = 401;

      ctx.body = {
        code: 0,
        msg: "账户或密码错误",
      };
    }
  }

  // 用户信息
  async userInfo() {
    const { ctx, app } = this;

    const { authorization } = ctx.request.headers;

    try {
      const id = jwt.verify(authorization, "1908A");

      const data = await app.mysql.get("user", { id });

      ctx.body = {
        code: 1,
        data,
      };
    } catch (error) {
      ctx.status = 401;

      ctx.body = {
        code: 0,
        msg: "登录已过期",
      };
    }
  }
}

module.exports = LoginController;
